package de.wbh.gwt.form.layouter.java.server.servlet;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.wbh.gwt.form.layouter.java.server.ConfigurationHelper;
import de.wbh.gwt.form.layouter.java.server.PdfToImageConverter;

/**
 * Servlet das File (efd oder pdf)von der url runter und speichert es im entsprechenden Verzeichnis
 * 
 * @author Jenny
 * 
 */
public class DownloadFileServlet extends HttpServlet {

	private String UPLOAD_DIRECTORY;

	private final String HOMEDIR = ConfigurationHelper.getInstance().getHomeDirectory();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		boolean isPdf = false;
		String filename = req.getParameter("filename");
		String urlString = req.getParameter("url");
		BufferedInputStream in = null;
		FileOutputStream out = null;
		try {
			if (urlString.startsWith("www.")) {
				urlString = "http://" + urlString;
			}
			URL url = new URL(urlString);
			in = new BufferedInputStream(url.openStream());
			if (filename.endsWith("pdf") || filename.endsWith("PDF")) {
				isPdf = true;
				this.UPLOAD_DIRECTORY = this.HOMEDIR + "\\pdf";
			} else {
				this.UPLOAD_DIRECTORY = this.HOMEDIR + "\\efd";
			}

			if (!new File(this.UPLOAD_DIRECTORY).exists()) {
				new File(this.UPLOAD_DIRECTORY).mkdirs();
			}
			File downloadedFile = new File(this.UPLOAD_DIRECTORY, filename);
			if (!downloadedFile.exists()) {
				out = new FileOutputStream(downloadedFile);
				int read = 0;
				byte[] bytes = new byte[102400];
				while ((read = in.read(bytes)) != -1) {
					out.write(bytes, 0, read);
				}
				// Todo pdf in image umwandeln und im Ordner image ablegen , zur Zeit wird immer nur die erste Seite umgewandelt
				if (isPdf) {
					PdfToImageConverter converter = new PdfToImageConverter();
					converter.convert(this.HOMEDIR + "\\image", downloadedFile);
				}
				res.setStatus(HttpServletResponse.SC_OK);
				res.getWriter().print("Datei wurde erfolgreich abgelegt.");
				res.flushBuffer();
			} else {
				res.getWriter().print("Die Datei exsistiert schon.");
				res.setStatus(HttpServletResponse.SC_CONFLICT);

			}
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}
}
